package com.xq.config;

import com.xq.pojo.Configuration;
import com.xq.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperConfig {
    private Configuration configuration;

    public XMLMapperConfig(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 处理完整个增删改的sql及其参数映射
     * @param InputStream
     * @throws Exception
     */
    public void pares(InputStream InputStream) throws Exception {

        //j解析mapper.xml
        Document document = new SAXReader().read(InputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        //只需要list 和 namespace
        createMappedStatement(list, namespace);

        //更新的映射集合
        List<Element> updateList = rootElement.selectNodes("//update");
        //只需要list 和 namespace
        createMappedStatement(updateList, namespace);

        //插入的映射集合
        List<Element> insertList = rootElement.selectNodes("//insert");
        //只需要list 和 namespace
        createMappedStatement(insertList, namespace);
        //删除的映射集合
        List<Element> deleteList = rootElement.selectNodes("//delete");
        //只需要list 和 namespace
        createMappedStatement(deleteList, namespace);


    }

    private void createMappedStatement(List<Element> list, String namespace) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
